package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.tea.TeaException;
import com.ruoyi.system.config.FastDFSClient;
import com.ruoyi.system.config.HttpUtils;
import com.ruoyi.system.domain.Merchant;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;

import com.ruoyi.system.service.IMerchantService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商家Controller
 * 
 * @author ruoyi
 * @date 2023-02-01
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController extends BaseController
{
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private OSS client;



    @Value("${oss.hostName}")
    String hostName;
    @Value("${oss.bucket}")
    String bucket;
    private static  String name1="";
    private static  String idcard1="";
    private static  String Url1="";


    /**
     * 查询商家列表
     */
    @RequiresPermissions("system:merchant:list")
    @GetMapping("/list")
    public TableDataInfo list(Merchant merchant)
    {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }

    /**
     * 导出商家列表
     */
    @RequiresPermissions("system:merchant:export")
    @Log(title = "商家", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Merchant merchant)
    {
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        util.exportExcel(response, list, "商家数据");
    }

    /**
     * 获取商家详细信息
     */
    @RequiresPermissions("system:merchant:query")
    @GetMapping(value = "/{mid}")
    public AjaxResult getInfo(@PathVariable("mid") Long mid)
    {
        return AjaxResult.success(merchantService.selectMerchantByMid(mid));
    }

    /**
     * 新增商家
     */
    @RequiresPermissions("system:merchant:add")
    @Log(title = "商家", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.insertMerchant(merchant));
    }

    /**
     * 修改商家
     */
    @RequiresPermissions("system:merchant:edit")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 删除商家
     */
    @RequiresPermissions("system:merchant:remove")
    @Log(title = "商家", businessType = BusinessType.DELETE)
	@DeleteMapping("/{mids}")
    public AjaxResult remove(@PathVariable Long[] mids)
    {
        return toAjax(merchantService.deleteMerchantByMids(mids));
    }

    @PostMapping("idcheck1/{id}/{name}")
    public String check(@PathVariable String id,@PathVariable String name) throws IOException {

        String url = "https://idcardv2.shumaidata.com/new-idcard";
        String appCode = "2c6ec7bdcf3549b1bceba11182984c7c";
        Map<String, String> params = new HashMap<>();
        params.put("idcard", id);
        params.put("name", name);
        name1=name;
        idcard1=id;
        String result = get(appCode, url, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");

        return code;
    }
    public static String get(String appCode, String url, Map<String, String> params) throws IOException {
        url = url + buildRequestUrl(params);
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }
    public static String buildRequestUrl(Map<String, String> params) {
        StringBuilder url = new StringBuilder("?");
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            url.append(key).append("=").append(params.get(key)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }
    @GetMapping("bankCheck/{bankcard}")
    public String bankCheck(@PathVariable String bankcard) throws IOException {
        String url = "https://slycard3.market.alicloudapi.com/bankcard3check";
        String appCode = "2c6ec7bdcf3549b1bceba11182984c7c";

        Map<String, String> params = new HashMap<>();
        params.put("idcard", idcard1);
        params.put("name", name1);
        params.put("bankcard", bankcard);

        String result = get1(appCode, url, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");

        return code;
    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String get1(String appCode, String url, Map<String, String> params) throws IOException {
        url = url + buildRequestUrl1(params);
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }

    public static String buildRequestUrl1(Map<String, String> params) {
        StringBuilder url = new StringBuilder("?");
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            url.append(key).append("=").append(params.get(key)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }
    @Autowired
    private FastDFSClient fastDFSClient;

    @PostMapping("fastdfs")
    public String fastDFSUpload(@RequestParam("file") MultipartFile file){

        String url = fastDFSClient.upload(file);
        if(url!=null){
            return url ;
        }
        return "失败";
    }
    @PostMapping("oss")
    public String ossUpload(@RequestParam("file") MultipartFile file) throws IOException {

            //OSS
            String fileName =  file.getOriginalFilename();
            client.putObject(bucket,fileName,file.getInputStream());
            String url=hostName+fileName;
            Url1=url;
            return url;
    }
    public static com.aliyun.ocr_api20210707.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            // 必填，您的 AccessKey ID
            .setAccessKeyId("LTAI5tRj7DUJTDqmGUNdMnhM")
            // 必填，您的 AccessKey Secret
            .setAccessKeySecret("eP9rRc87kAkMPSEMNDJCfUUowpwRA4");
    // 访问的域名
    config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
    return new com.aliyun.ocr_api20210707.Client(config);
}

    @GetMapping("businessCheck")
    public boolean businessCheck() throws Exception {
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.ocr_api20210707.Client client = MerchantController.createClient("LTAI5tRj7DUJTDqmGUNdMnhM", "eP9rRc87kAkMPSEMNDJCfUUowpwRA4");
        com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest()
                .setUrl(Url1);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.recognizeBusinessLicenseWithOptions(recognizeBusinessLicenseRequest, runtime);
            return true;
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);

        }
        return false;
    }
}
